package com.kreao.korean.controller;

import com.kreao.korean.dto.ApiResponse;
import com.kreao.korean.dto.StudyRequest;
import com.kreao.korean.dto.StudyStatistics;
import com.kreao.korean.entity.StudyRecord;
import com.kreao.korean.security.UserPrincipal;
import com.kreao.korean.service.interfaces.StudyService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/study")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class StudyController {
    
    private final StudyService studyService;
    
    /**
     * 记录学习
     */
    @PostMapping("/record")
    public ResponseEntity<?> recordStudy(
            @Valid @RequestBody StudyRequest request,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            StudyRecord record = studyService.recordStudy(request, userPrincipal.getId());
            return ResponseEntity.ok(ApiResponse.success("学习记录保存成功", record));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("学习记录保存失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取学习统计
     */
    @GetMapping("/statistics")
    public ResponseEntity<?> getStudyStatistics(
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            StudyStatistics statistics = studyService.getStudyStatistics(userPrincipal.getId());
            return ResponseEntity.ok(ApiResponse.success(statistics));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("获取学习统计失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取最近学习数据
     */
    @GetMapping("/recent")
    public ResponseEntity<?> getRecentStudyData(
            @RequestParam(defaultValue = "30") int days,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            StudyStatistics statistics = studyService.getRecentStudyData(userPrincipal.getId(), days);
            return ResponseEntity.ok(ApiResponse.success(statistics));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("获取最近学习数据失败: " + e.getMessage()));
        }
    }
} 